package com.team9.fitness.service;

import com.team9.fitness.entity.PostComment;
import com.team9.fitness.mapper.PostCommentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 帖子评论服务类
 * 
 * 提供帖子评论相关的业务逻辑：
 * - 评论管理：创建、更新、删除评论
 * - 查询功能：支持按帖子、用户、ID查询，支持排序
 * - 统计功能：统计评论的点赞数量
 * - 状态管理：支持用户点赞状态查询
 */
@Service
@Transactional
@Slf4j
public class PostCommentService {

    @Autowired
    private PostCommentMapper postCommentMapper;

    @Autowired
    private CommunityPostService communityPostService;

    /**
     * 创建评论
     */
    @CacheEvict(value = {"postComments", "communityPosts"}, allEntries = true)
    public PostComment createComment(PostComment comment) {
        log.info("创建帖子评论: postId={}, userId={}", comment.getPostId(), comment.getUserId());

        // 初始化统计字段
        comment.initializeCounts();
        comment.setCreatedAtIfNull();

        postCommentMapper.insert(comment);
        log.info("创建帖子评论成功: id={}", comment.getId());

        return comment;
    }

    /**
     * 根据帖子ID获取评论列表（包含统计信息）
     */
    @Cacheable(value = "postComments", key = "'post_' + #postId + '_' + #currentUserId")
    public List<PostComment> getCommentsByPostId(Long postId, Long currentUserId) {
        log.info("获取帖子评论: postId={}, currentUserId={}", postId, currentUserId);
        return postCommentMapper.selectByPostIdWithStatsOrderByCreatedAtAsc(postId, currentUserId);
    }

    /**
     * 根据用户ID获取评论列表（包含统计信息）
     */
    public List<PostComment> getCommentsByUserId(Long userId, Long currentUserId) {
        log.info("获取用户评论: userId={}, currentUserId={}", userId, currentUserId);
        return postCommentMapper.selectByUserIdWithStatsOrderByCreatedAtDesc(userId, currentUserId);
    }

    /**
     * 根据ID获取评论（包含统计信息）
     */
    public Optional<PostComment> getCommentById(Long id, Long currentUserId) {
        log.info("根据ID获取评论: id={}, currentUserId={}", id, currentUserId);
        return postCommentMapper.selectByIdWithStats(id, currentUserId);
    }

    /**
     * 根据评论ID获取回复列表（包含统计信息）
     */
    public List<PostComment> getRepliesByCommentId(Long commentId, Long currentUserId) {
        log.info("获取评论回复: commentId={}, currentUserId={}", commentId, currentUserId);
        
        // 先测试简单查询
        int count = postCommentMapper.countRepliesByCommentId(commentId);
        log.info("简单查询回复数量: {}", count);
        
        List<PostComment> replies = postCommentMapper.selectRepliesByCommentIdWithStats(commentId, currentUserId);
        log.info("复杂查询回复数量: {}", replies.size());
        for (PostComment reply : replies) {
            log.info("回复详情: id={}, parentId={}, rootId={}, content={}", 
                reply.getId(), reply.getParentId(), reply.getRootId(), reply.getContent());
        }
        return replies;
    }

    /**
     * 更新评论
     */
    public PostComment updateComment(PostComment comment) {
        log.info("更新评论: id={}", comment.getId());

        postCommentMapper.updateById(comment);
        log.info("更新评论成功: id={}", comment.getId());

        return comment;
    }

    /**
     * 删除评论
     */
    public void deleteComment(Long id) {
        log.info("删除评论: id={}", id);
        postCommentMapper.deleteById(id);
        log.info("删除评论成功: id={}", id);
    }

    /**
     * 删除评论（带权限检查）
     */
    public boolean deleteComment(Long commentId, Long userId) {
        try {
            log.info("删除评论: commentId={}, userId={}", commentId, userId);
            
            // 检查评论是否存在且属于该用户
            Optional<PostComment> commentOpt = postCommentMapper.selectById(commentId);
            if (!commentOpt.isPresent()) {
                log.warn("评论不存在: commentId={}", commentId);
                return false;
            }
            
            PostComment comment = commentOpt.get();
            if (!comment.getUserId().equals(userId)) {
                log.warn("用户无权限删除此评论: commentId={}, userId={}, commentUserId={}", commentId, userId, comment.getUserId());
                return false;
            }
            
            postCommentMapper.deleteById(commentId);
            log.info("删除评论成功: commentId={}, userId={}", commentId, userId);
            return true;
        } catch (Exception e) {
            log.error("删除评论失败: commentId={}, userId={}", commentId, userId, e);
            return false;
        }
    }

    /**
     * 获取用户评论列表（分页）
     */
    public List<PostComment> getUserComments(Long userId, int page, int size) {
        log.info("获取用户评论列表: userId={}, page={}, size={}", userId, page, size);
        
        int offset = (page - 1) * size;
        return postCommentMapper.selectByUserIdWithStatsOrderByCreatedAtDescPaged(userId, null, offset, size);
    }

    /**
     * 获取用户评论总数
     */
    public int getUserCommentCount(Long userId) {
        log.info("获取用户评论总数: userId={}", userId);
        return postCommentMapper.countByUserId(userId);
    }

    /**
     * 获取帖子评论总数
     */
    public int countByPostId(Long postId) {
        log.info("获取帖子评论总数: postId={}", postId);
        return postCommentMapper.countByPostId(postId);
    }

    /**
     * 添加评论业务逻辑（供ZRDDS调用）
     */
    public PostComment addCommentByZRDDS(Long userId, Long postId, String content, Long parentId, Long rootId) {
        try {
            log.info("添加评论: userId={}, postId={}, parentId={}, rootId={}", userId, postId, parentId, rootId);

            PostComment comment = new PostComment();
            comment.setUserId(userId);
            comment.setPostId(postId);
            comment.setContent(content);
            comment.setParentId(parentId);
            comment.setRootId(rootId);
            comment.initializeCounts();
            comment.setCreatedAtIfNull();

            postCommentMapper.insert(comment);
            log.info("添加评论成功: id={}", comment.getId());

            // 更新帖子的评论数量
            updatePostCommentCount(postId);

            return comment;
        } catch (Exception e) {
            log.error("添加评论失败: userId={}, postId={}", userId, postId, e);
            return null;
        }
    }

    /**
     * 添加评论业务逻辑（供ZRDDS调用）- 兼容旧版本
     */
    public PostComment addCommentByZRDDS(Long userId, Long postId, String content) {
        return addCommentByZRDDS(userId, postId, content, null, null);
    }

    /**
     * 更新帖子的评论数量
     */
    private void updatePostCommentCount(Long postId) {
        try {
            int commentCount = postCommentMapper.countByPostId(postId);
            communityPostService.updatePostCommentCount(postId, commentCount);
            log.info("更新帖子评论数量: postId={}, commentCount={}", postId, commentCount);
        } catch (Exception e) {
            log.error("更新帖子评论数量失败: postId={}", postId, e);
        }
    }

    /**
     * 更新评论点赞数量
     */
    public void updateCommentLikeCount(Long commentId, Integer likeCount) {
        try {
            postCommentMapper.updateLikeCount(commentId, likeCount);
            log.debug("更新评论点赞数量: commentId={}, likeCount={}", commentId, likeCount);
        } catch (Exception e) {
            log.error("更新评论点赞数量失败: commentId={}, likeCount={}", commentId, likeCount, e);
        }
    }

    /**
     * 根据帖子ID获取前N条评论（快速加载）
     */
    @Cacheable(value = "postComments", key = "'post_' + #postId + '_limit_' + #limit + '_' + #currentUserId")
    public List<PostComment> getCommentsByPostIdWithLimit(Long postId, Integer limit, Long currentUserId) {
        log.info("获取帖子前{}条评论: postId={}, currentUserId={}", limit, postId, currentUserId);
        return postCommentMapper.selectByPostIdWithStatsOrderByCreatedAtAscLimit(postId, currentUserId, limit);
    }

    /**
     * 根据帖子ID分页获取评论（后台补充加载）
     */
    @Cacheable(value = "postComments", key = "'post_' + #postId + '_offset_' + #offset + '_limit_' + #limit + '_' + #currentUserId")
    public List<PostComment> getCommentsByPostIdWithPagination(Long postId, Integer offset, Integer limit, Long currentUserId) {
        log.info("分页获取帖子评论: postId={}, offset={}, limit={}, currentUserId={}", postId, offset, limit, currentUserId);
        return postCommentMapper.selectByPostIdWithStatsOrderByCreatedAtAscPagination(postId, currentUserId, offset, limit);
    }
}
